<template>
  <u-navbar
      :autoBack="true"
      bgColor="transparent"
  >
  </u-navbar>
  <navigator :url="`/pages/my/alterBackGround?url=${backgroundUrl}&ownerId=${ownerId}`"
             :style="{backgroundImage: 'url(' + backgroundUrl + ')'}" class="container">
    <view class="userinfo">
    </view>

  </navigator>
  <view class="content">
    <Cropper
        v-if="showCropper"
        @close="showCropper=false"
        @drawSuccess="drawSuccess"
        @drawFail="drawFail"
        @uploadSuccess="uploadSuccess"
        @uploadFail="uploadFail"
        shape="circle"
    ></Cropper>
    <!--    <okingtz-cropper @uploadSuccess="uploadSuccess"></okingtz-cropper>-->
    <view @tap="alterAvatar" class="avatar-container">
      <image :src="avatar" mode="scaleToFill" class="avatar"></image>
      <view class="change-avatar">
        <u-icon size="30" color="white" name="camera-fill"></u-icon>
        <text style="color: white;font-size: 16px">更换头像</text>
      </view>

    </view>
    <!--    更改姓名-->
    <navigator :url="`/pages/my/alterName?username=${username}`" class="cell-wrapper">
      <view class="cell-text">
        <text class="title">名字</text>
        <text class="value">{{ username }}</text>
      </view>
      <image class="right-icon"
             src="https://www.douluodalu.icu:9000/school/static/right.png"
             mode="widthFix"
      ></image>
    </navigator>

    <!--    更改简介-->
    <navigator :url="`/pages/my/alterIntroduction?introduction=${introduction}`"
               class="cell-wrapper">
      <view class="cell-text">
        <text class="title">简介</text>
        <text class="value" :style="{color: introduction == '' ? 'rgba(84,87,87,0.42)'  : '#000'}">
          {{ introduction == '' ? '介绍喜好、个性' : introduction }}
        </text>
      </view>
      <image class="right-icon"
             src="https://www.douluodalu.icu:9000/school/static/right.png"
             mode="widthFix"
      ></image>
    </navigator>

    <!--    更改性别-->
    <view @click="showSexActionSheet = true" class="cell-wrapper">
      <view class="cell-text">
        <text class="title">性别</text>
        <text class="value"
              :style="{color: (sex == null|| sex == undefined|| sex == 3) ? 'rgba(84,87,87,0.42)'  : '#000'}">
          <text v-if=" sex == null|| sex == undefined|| sex == 3">填写性别</text>
          <text v-if="sex == 1">男</text>
          <text v-if="sex == 0">女</text>
        </text>
      </view>
      <image class="right-icon"
             src="https://www.douluodalu.icu:9000/school/static/right.png"
             mode="widthFix"
      ></image>
    </view>

    <!--    更改生日-->
    <view class="cell-wrapper" @click="showDatetimePicker = true">
      <view class="cell-text">
        <text class="title">生日</text>
        <text class="value" :style="{color: birthday == '' ? 'rgba(84,87,87,0.42)'  : '#000'}">
          {{ birthday == '' ? '填写生日' : birthday }}
        </text>
      </view>
      <image class="right-icon"
             src="http://49.233.248.28:9000/school/static/right.png"
             mode="widthFix"
      ></image>
    </view>

    <!--    更改位置-->
    <navigator :url="`/pages/my/alterLocation`" class="cell-wrapper">
      <view class="cell-text">
        <text class="title">所在地</text>
        <text v-if="(location.country != '' && location?.country !== undefined) &&
        (location.province.trim() != '' && location?.province !== undefined) &&
        (location.city != '' && location?.city !== undefined)" class="value" style="margin-left: -1rem;color: #000">
          {{ location.country + ' . ' + location.province + ' . ' + location.city }}
        </text>
        <text v-else-if="(location.country != '' && location?.country !== undefined) &&
        (location.province.trim() == '' || location?.province == undefined) &&
        (location.city != '' && location?.city !== undefined)" class="value" style="margin-left: -1rem;color: #000">
          {{ location.country + ' . ' + location.city }}
        </text>
        <text v-else-if="(location.country != '' && location?.country !== undefined) &&
        (location.city == '' || location?.city == undefined) &&
        (location.province != '' && location?.province !== undefined)" class="value"
              style="margin-left: -1rem;color: #000">
          {{ location.country + ' . ' + location.province }}
        </text>
        <text v-else-if="(location.country != '' && location?.country !== undefined) &&
        (location.province.trim() == '' || location?.province == undefined) &&
        (location.city == '' && location?.city == undefined)" class="value" style="margin-left: -1rem;color: #000">
          {{ location.country }}
        </text>
        <text v-else class="value" style="margin-left: -1rem;color: rgba(84,87,87,0.42)">
          填写地区、发现同乡
        </text>
      </view>
      <image class="right-icon"
             src="http://49.233.248.28:9000/school/static/right.png"
             mode="widthFix"
      ></image>
    </navigator>

    <!--    更改学校-->
    <navigator url="/pages/my/alterSchool" class="cell-wrapper">
      <view class="cell-text">
        <text class="title">学校</text>
        <text class="value" :style="{color: school.trim() == '' ? 'rgba(84,87,87,0.42)'  : '#000'}">
          {{ school.trim() == '' ? '填写学校，发现校友' : school }}
        </text>
      </view>
      <image class="right-icon"
             src="http://49.233.248.28:9000/school/static/right.png"
             mode="widthFix"
      ></image>
    </navigator>

    <!--    更改性别-->
    <u-action-sheet @close="showSexActionSheet = false"
                    @select="alterUserSex"
                    cancelText="取消" :actions="sexActionList"
                    :show="showSexActionSheet">
    </u-action-sheet>

    <!--    更改生日-->
    <u-datetime-picker
        :show="showDatetimePicker"
        v-model="datetime"
        :minDate="minDate"
        :maxDate="maxDate"
        cancel-text="不展示"
        confirmColor="color: #ea4757"
        :closeOnClickOverlay="true"
        :formatter="formatter"
        @confirm="alterBirthday"
        @close="showDatetimePicker  = false"
        @cancel="notShowBirth"
        mode="date"
    ></u-datetime-picker>
  </view>
</template>

<script>

import OkingtzCropper from '@/uni_modules/okingtz-cropper/components/okingtz-cropper/okingtz-cropper'
import {alterFrontUserAvatar, alterFrontUserBirthday, alterFrontUserSex, getFrontUserInfo} from "@/api/user";
import index from "@/pages/index/index.vue";
import {getToken, getUserId} from "@/utils/auth";
import Cropper from '@/components/circle-avatar-cropper/cropper.vue'

export default {
  components: {
    //2.使用组件
    OkingtzCropper, Cropper
  },
  computed: {
    index() {
      return index
    }
  },
  data() {
    return {
      showCropper: false,
      sexActionList: [
        {
          name: '男',
        },
        {
          name: '女',
        },
        {
          name: '不展示', //开启后文字不显示
        }
      ],
      showSexActionSheet: false,
      showDatetimePicker: false,
      username: '',
      oversea: null,
      birthday: '',
      location: {
        country: '',
        province: '',
        city: ''
      },
      maxDate: new Date().getTime(),
      minDate: new Date(1900, 1, 1),
      datetime: Number(new Date()),
      school: '',
      userId: '',
      ownerId: '',
      avatar: '',
      backgroundUrl: '',
      sex: null,
      introduction: '介绍喜好、个性',
      uploading: false,
    }
  },
  onShow() {
    // if(!this.uploading){
    let userId = getUserId();
    this.ownerId = userId
    this.getMyInfo(userId)
    // }
    uni.$on('alterUserInfo', (res) => {
      // console.log("收到emit:")
      // console.log(res)
      if (res.success == true) {
        setTimeout(() => {
          uni.showToast({
            title: '设置成功',
            icon: 'none'
          })
        }, 1000)
      } else {
        setTimeout(() => {
          uni.showToast({
            title: '设置失败',
            icon: 'none'
          })
        }, 1000)
      }
    })
  },
  onLoad(options) {
    // console.log(options.userId)
  },
  unload() {
    uni.$off('alterLocation')
  },
  methods: {
    toAlterBackgroud(url) {
      let userId = getUserId();
      console.log(1111111111111)
      console.log(userId)
      uni.navigateTo({
        url: `/pages/my/alterBackGround?url=${url}&ownerId=${userId}`
      })
    },
    drawSuccess(res) {
      // console.log('裁切成功',res)
      this.showCropper = false
      let _this = this
      uni.uploadFile({
        url: this.$BASE_UPLOAD, //仅为示例，非真实的接口地址
        filePath: res.tempFilePath,
        name: 'file',
        header: {
          'Authorization': getToken(),
        },
        success: (uploadFileRes) => {
          let result = (JSON.parse(uploadFileRes.data)).data.url
          alterFrontUserAvatar(result).then(res => {
            if (res.code == 200 && res?.data === undefined) {
              _this.avatar = result
              setTimeout(() => {
                uni.showToast({
                  title: '设置成功',
                  icon: 'none'
                })
              }, 1000)
            } else {
              setTimeout(() => {
                uni.showToast({
                  title: res.data,
                  icon: 'none',
                  duration: 2000
                })
              }, 1000)
            }
          })

        },
        fail: (err) => {
          console.log(err)
        }
      })

    },
    drawFail(res) {
      console.log('裁切失败', res)
    },
    uploadSuccess(res) {
      console.log('上传成功', res)
    },
    uploadFail(res) {
      console.log('上传失败', res)
    },
    alterAvatar() {
      this.showCropper = true
      // this.uploading = true

    },
    async alterBirthday(date) {
      let datetime = this.result(date.value, date.mode);
      const res = await alterFrontUserBirthday(new Date(date.value))
      if (res.code == 200) {
        uni.showToast({
          title: '设置成功',
          icon: 'none'
        })
        this.birthday = datetime
      } else {
        uni.showToast({
          title: '设置失败'
        })
      }
      this.showDatetimePicker = false
    },
    async notShowBirth() {
      this.birthday = ''
      const res = await alterFrontUserBirthday(new Date('1900-01-01'))
      if (res.code == 200) {
        uni.showToast({
          title: '设置成功',
          icon: 'none'
        })
      } else {
        uni.showToast({
          title: '设置失败'
        })
      }
      this.showDatetimePicker = false
    }
    ,
    async alterUserSex(index) {
      let sex = index.name
      if (sex == '男') {
        this.sex = 1
      }
      if (sex == '女') {
        this.sex = 0
      }
      if (sex == '不展示') {
        this.sex = 3
      }
      alterFrontUserSex(this.sex).then(res => {
        if (res.code == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'none'
          })
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    }
    ,
    async getMyInfo(id) {
      const res = await getFrontUserInfo(id)
      if (res.code == 200) {

        this.username = res.data?.username === undefined ? '' : res.data?.username
        this.school = res.data?.school === undefined ? '' : res.data?.school
        this.oversea = res.data?.oversea
        this.userId = res.data?.userId
        this.birthday = (res.data?.birthday === undefined || res.data?.birthday == this.$NOT_SHOW_BIRTH) ? '' : res.data?.birthday
        this.location = res.data?.location.province === undefined ? {} : res.data?.location
        this.sex = res.data?.sex === undefined ? '' : res.data?.sex
        this.introduction = res.data?.introduction === undefined ? '' : res.data?.introduction
        this.avatar = res.data?.avatar
        this.backgroundUrl = res.data?.backgroundUrl === undefined ? this.$DEFAULT_BG : res.data?.backgroundUrl
      }
    }
    ,
    result(time, mode) {
      const timeFormat = uni.$u.timeFormat,
          toast = uni.$u.toast
      switch (mode) {
        case 'datetime':
          return timeFormat(time, 'yyyy-mm-dd hh:MM')
        case 'date':
          return timeFormat(time, 'yyyy-mm-dd')
        case 'year-month':
          return timeFormat(time, 'yyyy-mm')
        case 'time':
          return time
        default:
          return ''
      }
    }
    ,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      return value
    }
    ,
  }
}
</script>

<style scoped>
.container {
  background: no-repeat center center;
  background-size: cover;

}


.userinfo {
  padding: 0 1rem;
  display: flex;
  align-items: center;
  height: 14rem;
  box-shadow: inset 0px -38px 48px 0px #00000063;

}


.name text {
  font-weight: 530;
  font-size: 38rpx;
  margin-left: 20rpx;
}

.content {
  background-color: white;
  margin-top: -25px;
  border-top-left-radius: 25px;
  border-top-right-radius: 25px;
  padding: 0.8rem 1rem 0 1rem;
  height: 72vh;
}

.age image {
  width: 14px;
  height: 14px;
  padding-left: 4px;
}

.ip text {
  background-color: #dfdfdf;
  border-radius: 3px;
  padding: 3px;
}

.avatar-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-wrapper {

}

.avatar {
  width: 125px;
  height: 125px;
  border-radius: 50%;
  border: 3px solid white;
  margin-top: -80px;
  position: relative;
}

.change-avatar {
  position: absolute;
  width: 125px;
  height: 125px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  top: 135px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.cell-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px
}

.cell-text {
  display: flex;
  align-items: center;
  text-align: left
}

.title {
  color: rgba(0, 0, 0, 0.6);
}

.value {
  color: black;
  font-weight: bolder;
  padding-left: 4rem
}

.right-icon {
  width: 15px;
  height: 15px;
}
</style>
